import {handleActions} from 'redux-actions';
import initialState from '../inits/todo';
import {
  ADD_TODO,
  TOGGLE_TODO,
  COMPLETE_TODO,
  REMOVE_TODO,
  SET_FILTER
} from '../../constants';

export default handleActions({

  [ADD_TODO]: (state, action) => ({
    ...state,
    list: [
      ...state.list,
      {
        text: action.payload.text,
        completed: false
      }
    ]
  }),

  [TOGGLE_TODO]: (state, action) => ({
    ...state,
    list: state.list.map((item, index) => {
      if (index === action.payload.index) {
        return Object.assign({}, item, {
          completed: !item.completed
        });
      }
      return Object.assign({}, item);
    })
  }),

  [COMPLETE_TODO]: (state, action) => ({
    ...state,
    list: state.list.map((item, index) => {
      if (index === action.payload.index) {
        return Object.assign({}, item, {
          completed: true
        });
      }
      return Object.assign({}, item);
    })
  }),

  [REMOVE_TODO]: (state, action) => ({
    ...state,
    list: state.list.slice(0, action.payload.index).concat(state.slice(action.payload.index + 1, state.length))
  }),

  [SET_FILTER]: (state, action) => ({
    ...state,
    filter: action.payload.filter
  })

}, initialState);
